<template>
  <view class="login-wrap">
    <view class="login-container">
      <view class="header">
        <image src="/static/img/logo.png" class="logo" />
        <view class="title-group">
          <text class="brand-name">品铁计划</text>
          <text class="slogan">专业健身训练,助你突破极限</text>
        </view>
      </view>

      <view class="content">
        <view class="welcome-text">
          <text class="welcome">欢迎回来</text>
          <text class="sub-welcome">登录后开启您的专业健身之旅</text>
        </view>

        <view class="login-options">
          <button
            class="login-btn wechat-btn"
            open-type="getPhoneNumber"
            @getphonenumber="handleGetPhoneNumber"
          >
            <u-icon name="weixin-fill" size="30" color="#fff"></u-icon>
            <text>微信一键登录</text>
          </button>
        </view>
      </view>

      <view class="footer">
        <text class="footer-text">登录即表示同意</text>
        <text class="link">《用户协议》</text>
        <text class="footer-text">和</text>
        <text class="link">《隐私政策》</text>
      </view>
    </view>
  </view>
</template>

<script>
import {login} from "@/api/fit";
import {getToken, setToken} from "@/utils/auth";
import {wxLogin} from "@/utils/api";

export default {
  data() {
    return {
      scene: '', // 存储场景值
      scanParams: {} // 存储扫码参数
    }
  },
  onShow() {
   console.log('cesjo');

  },
  async onLoad(options) {
    // 获取页面参数
    console.log('页面参数:', options)
    // 获取场景值
    if(options.scene) {
      // scene需要解码
      this.scene = decodeURIComponent(options.scene)
      console.log('场景值:', this.scene)

      // 解析场景值中的参数
      try {
        // 假设场景值是key1=value1&key2=value2格式
        const params = {}
        this.scene.split('&').forEach(item => {
          const [key, value] = item.split('=')
          params[key] = value
        })
        this.scanParams = params
        console.log('解析后的扫码参数:', this.scanParams)
      } catch(err) {
        console.log('场景值解析失败:', err)
      }
    }

    // 获取其他url参数
    if(options.q) {
      // 如果是通过二维码扫描进入,q参数会包含完整的url
      const qUrl = decodeURIComponent(options.q)
      try {
        const url = new URL(qUrl)
        this.scanParams = Object.fromEntries(url.searchParams)
        console.log('URL参数:', this.scanParams)
      } catch(err) {
        console.log('URL解析失败:', err)
      }
    }
    this.init()
  },
  methods: {
    init() {
      if (getToken()) {
        this.loginSuccess()
      }
    },
    handleGetPhoneNumber(e) {
      console.log('获取手机号回调:', e)
      if (e.detail.code) {
        // 用户允许获取手机号
        this.handleLogin(e.detail.code)
      } else {
        // 用户拒绝获取手机号
        uni.showToast({
          title: '需要授权手机号才能登录',
          icon: 'none'
        })
      }
    },
    handleLogin(phoneCode = null) {
      console.log('开始登录,phoneCode:', phoneCode)
      uni.login({
        provider: "weixin",
        onlyAuthorize: true,
        success: (event) => {
          console.log('uni.login成功:', event)
          let params = {
            username: event.code,
            tenantId: this.scanParams.tid || '',
            role: this.scanParams.role || ''
          }
          console.log(params,'params');
          login(params).then(res => {
            console.log('login:', res)
            const {code,data} = res;
         
            if (code === 200) {
              if (data.token) {
                console.log('已注册用户登录成功')
                setToken(data.token.toString())
                   //本地存储role
                uni.setStorageSync('role', data.role)
                uni.setStorageSync('role_id', data.id)
                uni.setStorageSync('role_name', data.nickName)
                // this.$store.commit('SET_TOKEN', data.token.toString())
                this.loginSuccess()
              } 
            } else {
              uni.showToast({
                title: res.msg || '登录失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            uni.showToast({
              title: '登录请求失败',
              icon: 'none'
            })
          })
        },
        fail(err) {
          console.error('uni.login失败:', err)
          uni.showToast({
            title: '登录失败,请重试',
            icon: 'none'
          })
        }
      })
    },
    loginSuccess() {
      console.log('准备开始跳转页面');
      // this.$tab.redirectTo('/pages/index/index')
      uni.redirectTo({
        url: '/pages/index/index'
      })
    }
  },
}
</script>

<style scoped lang="scss">
.login-wrap {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #f6f8fc 0%, #ffffff 100%);
  display: flex;
  align-items: center;
  justify-content: center;

  .login-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 60rpx 40rpx;

    .header {
      display: flex;
      align-items: center;
      margin-top: 80rpx;
      padding: 0 20rpx;

      .logo {
        width: 120rpx;
        height: 120rpx;
        margin-right: 30rpx;
      }

      .title-group {
        display: flex;
        flex-direction: column;
        gap: 10rpx;

        .brand-name {
          font-size: 44rpx;
          font-weight: 600;
          color: #333;
          letter-spacing: 2rpx;
        }

        .slogan {
          font-size: 26rpx;
          color: #666;
        }
      }
    }

    .content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-top: -100rpx;

      .welcome-text {
        text-align: center;
        margin-bottom: 80rpx;

        .welcome {
          display: block;
          font-size: 52rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 20rpx;
        }

        .sub-welcome {
          font-size: 28rpx;
          color: #666;
        }
      }

      .login-options {
        padding: 0 30rpx;

        .login-btn {
          height: 100rpx;
          border-radius: 50rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 32rpx;
          font-weight: 500;
          box-shadow: 0 8rpx 20rpx rgba(7, 193, 96, 0.2);
          transition: all 0.3s ease;
          &:active {
            transform: scale(0.98);
          }
          text {
            margin-left: 16rpx;
          }
        }
        .wechat-btn {
          background: #07c160;
          color: #fff;
        }
      }
    }

    .footer {
      text-align: center;
      font-size: 24rpx;
      color: #999;
      padding: 40rpx 0;

      .footer-text {
        margin: 0 6rpx;
      }

      .link {
        color: #07c160;
      }
    }
  }
}
</style>
